/**
 * src/pages/chef/orders/index.tsx
 * ------------------------------------
 * 厨师订单管理页面
 * 1. 展示所有订单列表，支持按状态筛选（全部/待处理/已确认/已完成/已取消）
 * 2. 提供订单操作：确认订单、完成订单、取消订单
 * 3. 实时显示订单状态、客户信息、菜品详情、价格等
 * 4. 支持刷新订单列表与返回上一页功能
 * 仅厨师角色可访问，依赖全局状态获取订单数据
 * 创建日期：2025-08-06
 */
import { View, Text, Button } from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { useState } from 'react'
import { useAppContext } from '../../../store'
import { formatPrice, getOrderStatusText, getOrderStatusColor, formatDateTime } from '../../../utils'
import { orderUtils } from '../../../utils/orderUtils'
import './index.scss'

export default function ChefOrders() {
  const { state, dispatch } = useAppContext()
  const { orders } = state
  const [filter, setFilter] = useState('all')
  const [isRefreshing, setIsRefreshing] = useState(false)

  // 重新加载数据
  useDidShow(() => {
    refreshOrders()
  })

  // 获取订单ID的短格式（微信小程序兼容）
  const getShortOrderId = (orderId: string) => {
    if (orderId.length <= 6) return orderId
    return orderId.substring(orderId.length - 6)
  }

  // 返回上一页
  const handleBack = () => {
    Taro.navigateBack().catch(() => {
      // 如果没有上一页，则返回到厨师主页
      Taro.navigateTo({ url: '/pages/chef/dashboard/index' })
    })
  }

  // 刷新订单列表
  const refreshOrders = async () => {
    try {
      setIsRefreshing(true)
      const { CloudDataManager } = await import('../../../utils/cloud')
      const freshOrders = await CloudDataManager.getOrders()
      dispatch({ type: 'SET_ORDERS', payload: freshOrders })
      Taro.showToast({ title: '刷新成功', icon: 'success', duration: 1500 })
    } catch (error) {
      console.error('刷新订单失败:', error)
      Taro.showToast({ title: '刷新失败', icon: 'error', duration: 1500 })
    } finally {
      setIsRefreshing(false)
    }
  }

  const handleAcceptOrder = async (orderId: string) => {
    try {
      if (!state.currentUser) {
        Taro.showToast({ title: '用户未登录', icon: 'error' })
        return
      }
      await orderUtils.updateOrderStatus(orderId, 'confirmed', state.currentUser)
      Taro.showToast({ title: '订单已确认', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: '操作失败', icon: 'error' })
    }
  }

  const handleCompleteOrder = async (orderId: string) => {
    try {
      if (!state.currentUser) {
        Taro.showToast({ title: '用户未登录', icon: 'error' })
        return
      }
      await orderUtils.updateOrderStatus(orderId, 'completed', state.currentUser)
      Taro.showToast({ title: '订单已完成', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: '操作失败', icon: 'error' })
    }
  }

  const handleCancelOrder = async (orderId: string) => {
    try {
      if (!state.currentUser) {
        Taro.showToast({ title: '用户未登录', icon: 'error' })
        return
      }
      await orderUtils.updateOrderStatus(orderId, 'cancelled', state.currentUser)
      Taro.showToast({ title: '订单已取消', icon: 'success' })
    } catch (error) {
      Taro.showToast({ title: '操作失败', icon: 'error' })
    }
  }

  // 筛选订单
  const filteredOrders = orders.filter(order => {
    if (filter === 'all') return true
    return order.status === filter
  })

  return (
    <View className='chef-orders'>
      <View className='header'>
        <View className='header-left'>
          <Button className='back-btn' onClick={handleBack}>
            返回
          </Button>
          <Text className='title'>厨师工作台</Text>
        </View>
        <Button 
          className='refresh-btn'
          onClick={refreshOrders}
          disabled={isRefreshing}
        >
          {isRefreshing ? '刷新中...' : '刷新订单'}
        </Button>
      </View>

      <View className='filter-tabs'>
        <View 
          className={`filter-tab ${filter === 'all' ? 'active' : ''}`}
          onClick={() => setFilter('all')}
        >
          全部订单
        </View>
        <View 
          className={`filter-tab ${filter === 'pending' ? 'active' : ''}`}
          onClick={() => setFilter('pending')}
        >
          待处理
        </View>
        <View 
          className={`filter-tab ${filter === 'confirmed' ? 'active' : ''}`}
          onClick={() => setFilter('confirmed')}
        >
          已确认
        </View>
        <View 
          className={`filter-tab ${filter === 'completed' ? 'active' : ''}`}
          onClick={() => setFilter('completed')}
        >
          已完成
        </View>
        <View 
          className={`filter-tab ${filter === 'cancelled' ? 'active' : ''}`}
          onClick={() => setFilter('cancelled')}
        >
          已取消
        </View>
      </View>

      <View className='orders-list'>
        {filteredOrders.length > 0 ? (
          filteredOrders.map(order => (
            <View key={order.id} className='order-item'>
              <View className='order-header'>
                <Text className='order-id'>订单 #{getShortOrderId(order.id)}</Text>
                <Text className='order-customer'>{order.userName || '顾客'}</Text>
                <Text className='order-time'>{formatDateTime(order.createdAt)}</Text>
              </View>
              
              <View className='order-items'>
                {order.items.map(item => (
                  <View key={item.dishId} className='order-item-detail'>
                    <Text className='item-name'>{item.dishName}</Text>
                    <Text className='item-quantity'>x{item.quantity}</Text>
                    <Text className='item-price'>{formatPrice(item.totalPrice)}</Text>
                  </View>
                ))}
              </View>
              
              <View className='order-footer'>
                <View className='order-total'>
                  <Text className='total-label'>总计:</Text>
                  <Text className='total-amount'>{formatPrice(order.finalAmount)}</Text>
                </View>
                
                <View className='order-status'>
                  <Text 
                    className='status-badge'
                    style={{ backgroundColor: getOrderStatusColor(order.status) }}
                  >
                    {getOrderStatusText(order.status)}
                  </Text>
                </View>
              </View>
              
              <View className='order-actions'>
                {order.status === 'pending' && (
                  <>
                    <Button 
                      className='action-btn accept-btn'
                      onClick={() => handleAcceptOrder(order.id)}
                    >
                      确认订单
                    </Button>
                    <Button 
                      className='action-btn cancel-btn'
                      onClick={() => handleCancelOrder(order.id)}
                    >
                      取消订单
                    </Button>
                  </>
                )}
                
                {order.status === 'confirmed' && (
                  <Button 
                    className='action-btn complete-btn'
                    onClick={() => handleCompleteOrder(order.id)}
                  >
                    完成订单
                  </Button>
                )}
              </View>
            </View>
          ))
        ) : (
          <View className='empty-state'>
            <Text className='empty-icon'>📋</Text>
            <Text className='empty-text'>暂无{filter !== 'all' ? getOrderStatusText(filter) : ''}订单</Text>
            <Text className='empty-desc'>
              {filter !== 'all' 
                ? '尝试切换到其他状态查看订单' 
                : '新的订单将会显示在这里'}
            </Text>
          </View>
        )}
      </View>
    </View>
  )
} 